package com.xca.gsondemo.utils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import android.os.AsyncTask;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.content.Context;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImageDownloader extends AsyncTask<String, Void, String> {

    private static final String TAG = "ImageDownloader";
    private Context context;
    private String downloadPath;

    public ImageDownloader(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(String... urls) {
        String imageUrl = urls[0];
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(imageUrl)
                .build();
        try (Response response = client.newCall(request).execute()) {
            InputStream is = response.body().byteStream();
            Bitmap bitmap = BitmapFactory.decodeStream(is);

            // 保存图片到内部存储
            downloadPath = saveBitmapToInternalStorage(bitmap);
            return downloadPath;
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "Error downloading image", e);
            return null;
        }
    }

    private String saveBitmapToInternalStorage(Bitmap bitmap) {
        File dir = context.getCacheDir(); // 或者 context.getExternalCacheDir() 用于外部存储
        File file = new File(dir, "downloaded_image.jpg");

        try (FileOutputStream fos = new FileOutputStream(file)) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            Log.i(TAG, "Image saved to: " + file.getAbsolutePath());
            return file.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "Error saving image", e);
            return null;
        }
    }

    @Override
    protected void onPostExecute(String result) {
        if (result != null) {
            Log.i(TAG, "Downloaded image path: " + result);
        } else {
            Log.e(TAG, "Failed to download the image.");
        }
    }
}